package com.order.listener;

import com.order.dao.entity.OrderInfo;
import com.order.dao.entity.Warehouse;
import com.order.dao.mapper.OrderInfoMapper;
import com.order.dao.mapper.WarehouseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    OrderInfoMapper orderInfoMapper;
    @Resource
    WarehouseMapper warehouseMapper;
    @Autowired
    StringRedisTemplate redisTemplate;


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    public void onMessage(Message message, byte[] pattern) {

        String expireKey = message.toString();

        if (expireKey.startsWith("order:")){

            Integer orderId = Integer.valueOf(expireKey.replace("order:",""));

            OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
            orderInfo.setStatus(2);
            orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
            System.out.println("订单失效，库存还原+1");
            Warehouse warehouse = warehouseMapper.selectByPrimaryKey(orderInfo.getCommodity());
            warehouse.setNum(warehouse.getNum()+1);
            warehouseMapper.updateByPrimaryKey(warehouse);

            redisTemplate.opsForValue().increment("num");
        }
    }

}

